<?php


namespace app\repository;


use app\model\DevelopUser;
use Tinywan\Jwt\JwtToken;

class IndexRepository extends Repository
{
    public function login($username, $password)
    {
        $model = DevelopUser::query()->where([
            "username"=>$username,
        ])->first();
        if (!$model){
            return $this->error("您输入的用户名有误");
        }
        $password_verify = password_verify($password, $model->password);

        if ($password_verify){
            $res = $model->toArray();
            unset($res['password']);
            $token = JwtToken::generateToken($res);
            return $this->success([
                "info"=>$res,
                "token"=>$token
            ]);
        }
        return $this->error("您输入的用户名或密码有误，请重新输入");
    }

    public function register($data)
    {
        $exists = DevelopUser::query()->where("name", $data['name'])->orWhere("username", $data['username'])->exists();
        if ($exists){
            return $this->error("您输入的用户名或姓名已经被占用，请重新输入");
        }
        $data['password'] = password_hash($data['password'],PASSWORD_DEFAULT);
        DevelopUser::query()->create($data);
        return $this->ok();
    }

}